-- 工具类
-- Author: Colocasia
-- Date: 2019-07-02

local string = require 'us.string';
local table = require 'us.table';
local bson = require 'bson';

local tool = {};


-- references -----
local table_insert = table.insert;
local table_concat = table.concat;

local string_byte = string.byte;
local string_format = string.format;
local string_match = string.match;
-- references -----


-- ip -----
local reg_ipv4 = "[0-9]+%.[0-9]+%.[0-9]+%.[0-9]+";
local reg_ipv6 = "[%da-fA-F]+:[%da-fA-F]+:[%da-fA-F]+:[%da-fA-F]+:[%da-fA-F]+:[%da-fA-F]+:[%da-fA-F]+:[%da-fA-F]+";
function tool:ip(addr)
    if not addr then return end
    
    local ip = {}
    -- ??ipv4
    local v4 = string_match(addr, reg_ipv4);
    local is_v4 = v4 ~= nil;
    ip.v4 = v4;
    ip.is_v4 = is_v4;

    -- ??ipv6
    local v6 = string_match(addr, reg_ipv6);
    local is_v6 = v6 ~= nil;
    ip.v6 = v6;
    ip.is_v6 = is_v6;

    return ip;
end
-- ip -----


-- guid -----
local function objectid2str(object_id)
    assert(type(object_id) == 'string' and string.len(object_id) == 14)

    local t = {}
    -- byte(1,2) represents the type is object_id binary type, we don't need it.
    for i = 3, 14 do
        local byte = string_byte(object_id, i)
        local high = (byte >> 4) & 0x0f
        local low = byte & 0x0f
        local s = string_format('%x%x', high, low)
        table_insert(t, s)
    end
    return table_concat(t)
end

function tool:guid()
    return objectid2str(bson.objectid())
end
-- guid -----

return tool;
